<template>
	<wsPage title="商品分类列表">
		<div slot="page_operate">
			<Button  @click="refresh">
                <Icon type="refresh"></Icon>
                <span>刷新</span>
            </Button>
		</div>
		<wsSmPanel>
			<div slot="list_operate">
				<Button  @click="showAddModal">添加分类</Button>
				<Button  @click="saveCategoryInRedis">缓存分类</Button>
				<Button  @click="repariData">数据修复</Button>
			</div>
			<div slot="list_data">
				<Alert show-icon>
			                        操作提示
			        <template slot="desc">
			          <p>1.点击类目名称可以查看其子类目</p>               
			          <p>2.只有最后一级类目才可以关联规格和参数属性</p> 
			        </template>
			    </Alert>
				<div class="title-row">
					<span style="">当前路径:</span>
					<span v-for="(item, index) in history.parents">
						<span v-if="index > 0" style="padding: 0 3px;">></span><a @click="listParent(item, index)" v-text="item.name"></a>
					</span>
				</div>
				<ws-table :data="table.data" style="width: 100%">
					<ws-table-column align="center" prop="name" label="名称">
						<template slot-scope="scope">
							<a @click="listChilds(scope.row)" v-if="scope.row.leafNodeType == 1">{{scope.row.name}}</a>
							<span v-if="scope.row.leafNodeType == 0" v-text="scope.row.name"></span>
						</template>
					</ws-table-column>
					<ws-table-column align="center" prop="goodsNum" label="商品数量" width="80"></ws-table-column>
					<ws-table-column align="center" prop="childsNum" label="子类目" width="80"></ws-table-column>
					<ws-table-column align="center" prop="wDesc" label="描述" min-width="180"></ws-table-column>
					<ws-table-column align="center" width="160" label="操作">
						<template slot-scope="scope">
							<Button @click="showEditModal(scope.row)" type="text" size="small">编辑</Button>
							<Button @click="showTranslateModal(scope.row)" type="text" size="small">翻译</Button>
							<Button @click="moveup(scope.row)" type="text" size="small" v-if="isSort && scope.$index != 0">上移</Button>
							<Button @click="movedown(scope.row)" type="text" size="small" v-if="isSort && scope.$index != table.data.length - 1">下移</Button>
        			<Button type="text" size="small" v-if="scope.row.leafNodeType == 0" @click="showSpecModal(scope.row)">规格</Button>
							<!--<Button type="text" size="small" v-if="scope.row.leafNodeType == 0" @click="showParamModal(scope.row)">参数</Button>-->	
      				</template>
					</ws-table-column>
				</ws-table>
			</div>
		</wsSmPanel>
		
		<!--新增属性弹框-->
		<wsModal v-model="modal.show" ok-text="保存" :title="modal.title"  @on-ok="modalSave"  @on-cancel="modalCancel">
		    <Form ref="modalForm" :model="modal.form" :rules="modal.validate" :label-width="100">
		        <FormItem label="父类目" required>
		            <span v-text="parentPath"></span>
		        </FormItem>
		        <FormItem label="名称" prop="name">
		            <Input v-model="modal.form.name" autofocus></Input>
		        </FormItem>
		        <FormItem label="允许子类目" prop="leafNodeType" v-if="isLeftNode">
		        	<i-switch v-model="modal.fields.leafNodeType"></i-switch>
		        </FormItem>
		        <FormItem label="描述" prop="wDesc">
		            <Input v-model="modal.form.wDesc" type="textarea"></Input>
		        </FormItem>
		    </Form>			
		</wsModal>	
		
		<!--规格参数模态框-->
		<wsModal v-model="modal1.show" :width="640" hide-footer ok-text="保存" :title="modal1.title"  @on-ok="modal1Save"  @on-cancel="modal1Cancel">
			<div>
				<Row class="title-row">
					<Col span="12" style="padding-right:10px">
			            <Select
			                v-model="modal1.form.value"
			                filterable
			                remote
			                :remote-method="propertyRemoteQuery"
			                :loading="modal1.form.loading">
			                <Option v-for="(option, index) in modal1.form.datas" :value="option.id" :label="option.name + '(' + option.code + ')'" :key="index"><span v-text="option.name"></span><span style="float:right;color:#ccc" v-text="option.code"></span></Option>
			            </Select>
			        </Col>
			        <Col span="12" style="padding-right:10px">
			        	<Button :disabled="isChecked" @click="addCategoryProperty">添加</Button>
			        </Col>
			    </Row>
				<ws-table :data="modal1.table.data" style="width: 100%">
					<ws-table-column align="center" prop="name" label="名称"></ws-table-column>
					<ws-table-column align="center" prop="code" label="CODE"></ws-table-column>
					<ws-table-column align="center" prop="wDesc" label="描述" min-width="120"></ws-table-column>
					<ws-table-column align="center" width="80" label="操作">
						<template slot-scope="scope">
        					<Button type="text" size="small" @click="delCategoryProperty(scope.row)">删除</Button>
      					</template>
					</ws-table-column>
				</ws-table>
			</div>	    			
		</wsModal>	
			
		<!--翻译内容弹框-->
		<wsModal v-model="modal2.show" ok-text="保存" title="类目翻译"  @on-ok="modal2Save"  @on-cancel="modal2Cancel">
		    <Form ref="modal2Form" :model="modal2.model" :rules="modal2.rules" :label-width="100">
		        <FormItem label="英文(en)" prop="name">
		            <Input  v-model="modal2.model.name"></Input>
		        </FormItem>
				<FormItem label="意文(it)" prop="name">
		            <Input  v-model="modal2.model.name2"></Input>
		        </FormItem>
		    </Form>	
		</wsModal>				
	</wsPage>
</template>

<script>
	import Util from '../../../common/util.js';
	import Common from '../../../common/common.js';
	export default {
		data() {
			return {
				params: {
					parentId: -1
				},
				table: {
					data: [],
				},
				history: {
					pages: [],
					parents: [{
						name: '首页',
						id: -1
					}]
				},
				modal: {
					show: false,
					title: '',
					form: {
						flag: '',
						parentId: '', 
						id: '',
						name: '',
						leafNodeType: 1,
						wDesc: '',
						childNum: 0,
						goodsNum: 0 //如果已经有商品关联也不允许修改
					},
					fields: {
						leafNodeType: true
					},
					validate: {
						name: [
	                        { required: true, message: '名称不能为空', trigger: 'blur' }
	                    ],
	                    leafNodeType: [
	                        { required: true, message: '必须选择' }
	                    ]
					}
				},
				//规格参数
				modal1: {
					show: false,
					title: '',
					table: {
						data: []
					},
					form: {
						loading: false,
						datas: [], //搜索结果
						type: '1', //1.规格 2.参数
						value: null,
						categoryId: null //当前目录
					}
				},
				modal2: {
					show: false,
					table: {
						datas: []
					},
					model: {
						categoryId: '',
						name: '',
						name2: '',
					},
					rules: {
						name: [{ required: true, message: '名称不能为空'}],
						name2: [{ required: true, message: '名称不能为空'}]
					}
				}
			}
		},
		computed: {
			isEdit() {
		      return !Util.vad.isBlank(this.modal.form.id);
		    },
		   /**
		    * 规格参数下拉是否选中
		    */
		    isChecked() {
		   	  	let value = this.modal1.form.value;
		    	return value == null;
		    },
		    isLeftNode() {
		    	if(!this.isEdit) {
		    		return true;
		    	}
		    	let r = this.isEdit && this.modal.form.childNum == 0 && this.modal.form.goodsNum == 0;
		    	return r;
		    },
		    parentPath() {
		    	let parents_ = this.history.parents;
		    	let r = '';
		    	for(let i = 0; i < parents_.length; i++) {
		    		if(0 != i) {
		    			r += '>';
		    		}
		    		r += parents_[i].name;
		    	}
		    	return r;
		    },
		    /**
		     * 是否可以排序,当列表长度大于1的时候
		     */
		    isSort() {
		    	return this.table.data.length > 1;
		    }
		},
		mounted() {
			this.init();
		},
		methods: {
			init() {
				this.query();
			},
			moveup(rowData) {
				this.modal.form.flag = "up";
				this.modal.form.id = rowData.id;
			    this.modal.form.parentId = this.params.parentId;
				this.updown();
			},
			movedown(rowData) {
				this.modal.form.flag = "down";
				this.modal.form.id = rowData.id;
			    this.modal.form.parentId = this.params.parentId;
				this.updown();
			},
			updown() {
			let postData_ = this.modal.form;
				const _this = this;
				this.axios.put('/ws/ops/v2/category/move', postData_).then(function(response) {
					let res = response.data;
					if(0 === res.meta.code) {
						_this.$Message.success('上移或下移操作成功');
						_this.init();
					} else {
						let message_ = res.meta.message;
						_this.$Message.warning('上移或下移操作失败:' + message_);
					}
				});
			},
			refresh() {
				this.query();
			},
			/**
			 * 查看列表
			 */
			query() {
				let parentId = this.params.parentId;
				const _this = this;
				this.axios.get('/ws/ops/v2/categorys/'+ parentId).then(response => {
					var res = response.data;
					var resMeta = res.meta;
					if (0 == resMeta.code) {
						_this.buildPageData(res.data);
					} else {
						_this.$Message.warning(resMeta.message);
					}
				});				
			},
			buildPageData(data_) {
				this.table.data = data_;
			},
			/**
			 * 获取子列表
			 */
			listChilds(row_) {
				this.history.parents.push({
					name: row_.name,
					id: row_.id
				});
				this.params.parentId = row_.id;
				this.query();
			},
			listParent(item_, index_) {
				//如果已经是最后了，就不用显示
				let parentLength = this.history.parents.length;
				if(index_ == parentLength - 1) {
					return;
				}
				//从数组中截掉
				this.params.parentId = item_.id;
				this.history.parents.splice(index_ + 1, parentLength - index_ - 1);
				this.query();
			},
			resetModalForm() {
				this.$refs['modalForm'].resetFields();
				this.modal.form.id = '';
				this.modal.form.name = '';
				this.modal.form.leafNodeType = 1;
				this.modal.form.wDesc = '';
				this.modal.form.childNum = 0;
				this.modal.form.goodsNum = 0;
				this.modal.fields.leafNodeType = true;
			},
			showAddModal() {
				this.modal.title='新增商品目录';
				this.modal.show = true;
			},
			/**
			 * 模态框保存
			 */
			modalSave() {
				this.$refs['modalForm'].validate((valid) => {
					if (valid) {
                        this.submitModal();
                    } 
               });
			},
			/**
			 * 提交模态框事件
			 */
			submitModal() {
				let isLeafNodeType = this.modal.fields.leafNodeType;
				this.modal.form.leafNodeType = isLeafNodeType ? 1 : 0;
				if(this.isEdit) {
					this.editModal();
				} else {
					this.saveModal();
				}
			},
			/**
			 * 保存模态框
			 */
			saveModal() {
				let postData_ = this.modal.form;
				const _this = this;
				let parentId = this.params.parentId;
				postData_.parentId = parentId;
				this.axios.post('/ws/ops/v2/category', postData_).then(function(response) {
					let res = response.data;
					if(0 === res.meta.code) {
						_this.$Message.success('新增商品类目成功');
						_this.modalCancel();
						_this.init();
					} else {
						let message_ = res.meta.message;
						_this.$Message.warning('新增商品类目失败:' + message_);
					}
				});
			},
			/**
			 * 修改模态框
			 */
			editModal() {
				let postData_ = this.modal.form;
				const _this = this;
				this.axios.put('/ws/ops/v2/category', postData_).then(function(response) {
					let res = response.data;
					if(0 === res.meta.code) {
						_this.$Message.success('修改商品类目成功');
						_this.modalCancel();
						_this.init();
					} else {
						let message_ = res.meta.message;
						_this.$Message.warning('修改商品类目失败:' + message_);
					}
				});
			},
			/**
			 * 模态框取消
			 */
			modalCancel() {
				this.resetModalForm();
				this.modal.show = false;
			},
            /**
			 * 打开新增模态框
			 */
			showEditModal(rowData){
				this.modal.title='修改商品类目';
				this.initModalData(rowData.id);
			},
			/**
			 * 初始化模态框数据
			 */
			initModalData(categoryId) {
				let _this = this;
				this.axios.get('/ws/ops/v2/category/' + categoryId).then(response => {
					var res = response.data;
					var resMeta = res.meta;
					if (0 == resMeta.code) {
						_this.buildModalData(res.data);
					} else {
						_this.$Message.warning(resMeta.message);
					}
				});
			},
			/**
			 * 构建模态框的图片
			 */
			buildModalData(data) {
				this.modal.form.id = data.id;
				this.modal.form.name = data.name;
				this.modal.form.leafNodeType = data.leafNodeType;
				this.modal.form.wDesc = data.wDesc;
				this.modal.form.childNum = data.childsNum;
				this.modal.form.goodsNum = data.goodsNum;
				this.modal.form.parentId = data.parentId;
				this.modal.fields.leafNodeType = (data.leafNodeType == 1 ? true : false);
				
				this.modal.show = true;
			},
			/**
			 * 显示规格模态框
			 */
			showSpecModal(row_) {
				this.modal1.show = true;
				this.modal1.title = '维护分类规格';
				let categoryId_  = row_.id;
				this.initCategoryPropertys(categoryId_, 1);
			},
			/**
			 * 显示参数模态框
			 */
			showParamModal(row_) {
				this.modal1.show = true;
				this.modal1.title = '维护分类参数';
				let categoryId_  = row_.id;
				this.initCategoryPropertys(categoryId_, 2);
			},
			/**
			 * 初始化分类的属性
			 * categoryId_ -- 分类编号
			 * type_ -- 列表
			 */
			initCategoryPropertys(categoryId_, type_) {
				this.modal1.form.categoryId = categoryId_;
				this.modal1.form.type = type_;
				const _this = this;
				this.axios.get('/ws/ops/v2/category/'+ categoryId_ + '/propertys/' + type_).then(response => {
					var res = response.data;
					var resMeta = res.meta;
					if (0 == resMeta.code) {
						_this.buildModal1PageData(res.data);
					} else {
						_this.$Message.warning(resMeta.message);
					}
				});
			},
			/**
			 * 构建模态框1的数据
			 */
			buildModal1PageData(data) {
				this.modal1.table.data = data;
			},
			/**
			 * 模态框1保存
			 */
			modal1Save() {
				this.modal1Cancel();
			},
			/**
			 * 模态框1取消
			 */
			modal1Cancel() {
				this.modal1.show = false;
				this.modal1.form.value = '';
			},
			/**
			 * 规格参数远程查询
			 */
			propertyRemoteQuery(key) {
				if(Util.vad.isBlank(key)) {
					this.modal1.form.value = null;
					this.buildRemoteQueryData([]);
					return;
				}
				const _this = this;
				let type = this.modal1.form.type;
				this.modal1.form.loading = true;
				this.axios.get('/ws/ops/v2/propertys', {params: {key: key, type: type}}).then(response => {
					_this.modal1.form.loading = false;
					var res = response.data;
					var resMeta = res.meta;
					if (0 == resMeta.code) {
						_this.buildRemoteQueryData(res.data);
					} else {
						_this.$Message.warning(resMeta.message);
					}
				});
			},
			buildRemoteQueryData(data) {
				this.modal1.form.datas = data;
			},
			/**
			 * 新增服务目录的规格参数
			 */
			addCategoryProperty() {
				let _this = this;
				let postData_ = {
					categoryId: this.modal1.form.categoryId,
					propertyId: this.modal1.form.value
				};
				
				this.axios.post('/ws/ops/v2/category/property', postData_).then(function(response) {
					let res = response.data;
					if(0 === res.meta.code) {
						_this.$Message.success('添加规格参数成功');
						_this.reloadCategoryPropertyTable();
					} else {
						let message_ = res.meta.message;
						_this.$Message.warning('添加规格参数失败:' + message_);
					}
				});
			},
			/**
			 * 重新加载目录规格参数
			 */
			reloadCategoryPropertyTable() {
				let categoryId_ = this.modal1.form.categoryId;
				let type_ = this.modal1.form.type;
				this.modal1.form.value = '';
				this.initCategoryPropertys(categoryId_, type_);
			},
			delCategoryProperty(row_) {
				let _this = this;
				let categoryId_ = this.modal1.form.categoryId;
				let propertyId = row_.propertyId;
				this.axios.delete('/ws/ops/v2/category/' + categoryId_ + '/property/' + propertyId).then(function(response) {
					let res = response.data;
					if(0 === res.meta.code) {
						_this.$Message.success('删除规格参数成功');
						_this.reloadCategoryPropertyTable();
					} else {
						let message_ = res.meta.message;
						_this.$Message.warning('删除规格参数失败:' + message_);
					}
				});
			},
			/**
			 * 修正规格顺序
			 */
			correctSpecOrder() {
				this.axios.get('/ws/ops/v2/category/correct/propertys').then(function(response) {
					let res = response.data;
					if(0 === res.meta.code) {
						_this.$Message.success('修正规格顺序成功');
					} else {
						let message_ = res.meta.message;
						_this.$Message.warning('修正规格顺序失败:' + message_);
					}
				});
			},
			/**
			 * 显示翻译
			 */
			showTranslateModal(row_) {
				const _this = this;
				this.modal2.model.categoryId = row_.id;
				this.axios.get('/ws/ops/v2/category/translates/' + row_.id).then(function(response) {
					let res = response.data;
					if(0 === res.meta.code) {
						_this.buildTranslateData(res.data);
					} else {
						let message_ = res.meta.message;
						_this.$Message.warning('加载翻译内容失败:' + message_);
					}
				});
				
			},
			buildTranslateData(data) {
				this.modal2.table.datas = data;
				//目录只处理英文，后面可以直接变成表格形式
				for(let i = 0; i < data.length; i++) {
					let tdata = data[i];
					if(tdata.languageCode == 'en') {
						this.modal2.model.name = tdata.name;
					}else if(tdata.languageCode == 'it'){
						this.modal2.model.name2 = tdata.name;
					}
					
				}
				this.modal2.show = true;
			},
			/**
			 * 翻译框保存操作
			 */
			modal2Save() {
				this.$refs['modal2Form'].validate((valid) => {
					if (valid) {
						this.submitModal2();
						this.submitModal3();
					} 
				});
			},
			/**
			 * 保存模态框
			 */
			submitModal2() {
				const _this = this;
				let postData_ = {
					categoryId: this.modal2.model.categoryId,
					name: this.modal2.model.name,
					languageCode: 'en'
				}
				this.axios.put('/ws/ops/v2/category/translates', postData_).then(function(response) {
					let res = response.data;
					if(0 === res.meta.code) {
						_this.$Message.success('添加商品类目翻译成功');
						_this.modal2Cancel();
					} else {
						let message_ = res.meta.message;
						_this.$Message.warning('添加商品类目翻译失败:' + message_);
					}
				});				
			},


			/**
			 * 保存模态框2
			 */
			submitModal3() {
				const _this = this;
				let postData_ = {
					categoryId: this.modal2.model.categoryId,
					name: this.modal2.model.name2,
					languageCode: 'it'
				}
				this.axios.put('/ws/ops/v2/category/translates', postData_).then(function(response) {
					let res = response.data;
					if(0 === res.meta.code) {
						//_this.$Message.success('添加商品类目翻译成功');
						_this.modal2Cancel();
					} else {
						let message_ = res.meta.message;
						//_this.$Message.warning('添加商品类目翻译失败:' + message_);
					}
				});				
			},

			
			modal2Cancel() {
				this.modal2.model.name = '';
				this.modal2.model.name2 = '';
				this.$refs['modal2Form'].resetFields();
				this.modal2.show = false;
			},
			saveCategoryInRedis(){
				const _this = this;
				this.axios.get('/ws/ops/v2/redis/category').then(function(response) {
					let res = response.data;
					if(0 === res.meta.code){
						_this.$Message.success('商品类目缓存成功');
					} else {
						_this.$Message.warning('商品类目缓存失败！');
					}
				})
			},
			/**
			 * 修复数据
			 */
			repariData() {
				const _this = this;
				this.axios.put('/ws/ops/v2/category/repari').then(function(response) {
					let res = response.data;
					if(0 === res.meta.code){
						_this.$Message.success('商品类目修复成功');
					} else {
						_this.$Message.warning('商品类目修复失败！');
					}
				})
			}
		}
	}
</script>

<style scoped>
	.ws-form-select {
		width: 162px;
	}
	.title-row {
		padding: 10px;
	}
</style>